package com.neuedu.demoweb.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * web操作辅助工具类
 * 
 * @author chens
 *
 */
public final class WebUtil {
	/**
	 * <pre>
	 * 所有的 controller servlet必须以sys作为前缀,
	 *   eg:   http://localhost:8088/demoweb/sys/admin/list
	 *         http://localhost:8088/sys/admin/list
	 * </pre>
	 */
	private static final String PREFIX = "sys";

	/**
	 * uri长度必须为4
	 */
	private static final int ARRAY_LENGTH = 4;

	/**
	 * <pre>
	 * 读取uri中包含的模块名称： 
	 *   eg:  http://localhost:8088/sys/admin/list  =>  admin
	 *        http://localhost:8088/demoweb/sys/food/list  =>  food
	 * </pre>
	 * 
	 * @param request
	 * @return
	 */
	public final static String getModel(HttpServletRequest request) {
		String uri = request.getRequestURI();
		uri = uri.replace(request.getContextPath(), "");
		String[] uris = uri.split("/");
		System.out.println(uris.length);
		if (uris.length == ARRAY_LENGTH && PREFIX.equals(uris[1])) {
			System.out.println(uris[2] + ": " + uris[3]);
			return uris[2];
		}
		return null;
	}

	/**
	 * <pre>
	 * 读取uri中包含的操作名称： 
	 *   eg:  http://localhost:8088/sys/admin/list  =>  list
	 *        http://localhost:8088/demoweb/sys/admin/add  =>  add
	 * </pre>
	 * 
	 * @param request
	 * @return
	 */
	public final static String getAction(HttpServletRequest request) {
		String uri = request.getRequestURI();
		uri = uri.replace(request.getContextPath(), "");
		String[] uris = uri.split("/");
		System.out.println(uris.length);
		if (uris.length == ARRAY_LENGTH && PREFIX.equals(uris[1])) {
			System.out.println(uris[2] + ": " + uris[3]);
			return uris[3];
		}
		return null;
	}

	/**
	 * 把对象转换成json并返回给客户端
	 * 
	 * @param response
	 * @param object
	 * @throws IOException
	 */
	public final static void writeJsonToClient(HttpServletResponse response, Object object) throws IOException {

		// 调用gson转换成json字符串
		Gson gson = null;
		//gson = new Gson();
		gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		
		String json = gson.toJson(object);
		System.out.println(json);
		// 把json字符串输出到浏览器
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(json);
		response.getWriter().flush();
	}
}
